import { App, mall, toast, navigate, storage } from '../../library/api/index'

Page({
  data: {
    products: [],
    navMall: 'on',
    cart: [],
    prices: {},
    tip: 'blank',
    tipData: {},
    swipers: {
      p70: ['https://r.epclass.meadjohnson.joypaw.com/p/v2/p0.png', 'https://r.epclass.meadjohnson.joypaw.com/p/v2/p70.png'],
      p90: ['https://r.epclass.meadjohnson.joypaw.com/p/v2/p0.png', 'https://r.epclass.meadjohnson.joypaw.com/p/v2/p90.png']
    },
    swiper: []
  },
  onLoad: function(e) {
    App.jice.onLoad(e)
  },
  onReady: function() {
    this.isNua()
    App.jice.track('page', {
      pagepath: '/pages/mall/index',
      pageTitle: '待产包-首页',
      pageType: 'view'
    })
    App.logger({
      type: App.G.view,
      channel: App.G.channel,
      target: '待产包-首页'
    })
  },
  onShow: function() {
    storage.remove('products').then(() => {
      this.getProducts()
    })
    App.jice.track('appshow')
  },
  onHide: function() {
    this.setData({
      products: [],
      cart: []
    })
  },
  isNua: function() {
    mall.isNua(r => {
      if(r.status) {
        this.setData({
          swiper: this.data.swipers.p70
        })
      } else {
        this.setData({
          swiper: this.data.swipers.p90
        })
      }
    }, r => {
      this.setData({
        swiper: this.data.swipers.p90
      })
    })
  },
  getProducts: function() {
    if(this.data.products.length == 0) {
      toast.show()
    }
    mall.getProducts(r => {
      toast.close(500)
      // 未注册跳转注册页面
      if(r.code == 201) {
        this.showRegisterTip()
      }
      // 用户已经购买待产包,跳转奶粉商城
      if(r.code == 202) {
        navigate.redirect(`/pages/mall/milk/index`)
      }
      if(r.code == 200) {
        this.data.products = []
        for(var i = 0; i < r.data.length; i++) {
          r.data[i]['is_add'] = false
          this.data.products.push(r.data[i])
        }
        this.setData({
          products: this.data.products
        })
        storage.set('products', this.data.products).then(() => {
          this.reloadCart()
        })
      }
      if(r.code >= 400) {
        this.setData({
          tip: 'tip',
          tipData: r.data
        })
      }
    }, r => {
      this.setData({
        tip: 'error_tip',
        tipData: `系统错误[${r.message}]，请稍后再试~`
      })
    })
  },
  view: function(e) {
    navigate.to(`/pages/mall/package/view/index?pid=${e.currentTarget.dataset.pid}`)
  },
  addCart: function(e) {
    var pid = e.currentTarget.dataset.pid
    storage.get('cart_items').then(items => {
      if(!items) {
        items = []
        items.push(pid)
      } else {
        let isAdded = false
        let isRedeem = false
        for(let i = 0; i < items.length; i++) {
          if(items[i] == pid) {
            isAdded = true
            break
          }
        }
        for(let i = 0; i < this.data.products.length; i++) {
          if(this.data.products[i].id == pid && this.data.products[i].type == 2) {
            isRedeem = true
            break
          }
        }
        if(!isAdded && !isRedeem) {
          items.push(pid)
        }
        // 排除已经添加的,先删除全部提货券然后添加添加当前提货券
        if(!isAdded && isRedeem) {
          for(let m = 0; m < items.length; m++) {
            for(let n = 0; n < this.data.products.length; n++) {
              if(items[m] == this.data.products[n].id && this.data.products[n].type == 2) {
                items.splice(m, 1)
                break
              }
            }
          }
          items.push(pid)
        }
      }
      storage.set('cart_items', items).then(() => {
        this.reloadCart()
      })
    })
  },
  removeCart: function(e) {
    var pid = e.currentTarget.dataset.pid
    storage.get('cart_items').then(items => {
      if(items) {
        for(let i = 0; i < items.length; i++) {
          if(items[i] == pid) {
            items.splice(i, 1)
            break
          }
        }
      }
      storage.set('cart_items', items).then(() => {
        this.reloadCart()
      })
    })
  },
  reloadCart: function() {
    storage.get('cart_items').then(items => {
      let mySumPrice = 0
      let sumPrice = 0
      if(items && items.length > 0) {
        let products = new Array()
        for(let i = 0; i < this.data.products.length; i++) {
          products[this.data.products[i]['id']] = {
            marketprice: this.data.products[i].marketprice,
            my_price: this.data.products[i].my_price,
          }
        }
        for(let i = 0; i < items.length; i++) {
          if(products[items[i]] !== undefined) {
            mySumPrice += products[items[i]].my_price
            sumPrice += products[items[i]].marketprice
          } else {
            // 产品已经不存在
            items.splice(i, 1)
          }
        }
        for(let i = 0; i < this.data.products.length; i++) {
          let isAdd = false
          for(let j = 0; j < items.length; j++) {
            if(this.data.products[i]['id'] == items[j]) {
              isAdd = true
            }
          }
          this.data.products[i]['is_add'] = isAdd
        }
      } else {
        items = []
        for(let i = 0; i < this.data.products.length; i++) {
          this.data.products[i]['is_add'] = false
        }
      }
      storage.set('cart_items', items).then(() => {
        this.setData({
          cart: {
            items: items,
            mySumPrice: Math.ceil(mySumPrice * 100) / 100,
            sumPrice: Math.ceil(sumPrice * 100) / 100
          },
          products: this.data.products
        })
      })
    })
  },
  clearCart: function() {
    storage.remove('cart_items').then(() => {
      this.reloadCart()
    })
  },
  settlement: function() {
    let items = this.data.cart.items
    if(items.length == 0) {
      return
    }
    let packageCount = 0
    let redeemCount = 0
    for(let m = 0; m < items.length; m++) {
      for(let n = 0; n < this.data.products.length; n++) {
        if(items[m] == this.data.products[n].id && this.data.products[n].type == 2) {
          redeemCount++
          break
        }
        if(items[m] == this.data.products[n].id && this.data.products[n].type != 2) {
          packageCount++
          break
        }
      }
    }
    let hasRedeem = false
    for(let n = 0; n < this.data.products.length; n++) {
      if(this.data.products[n].type == 2 && (this.data.products[n].vrlimit - this.data.products[n].vrredeemcount) > 0) {
        hasRedeem = true
        break
      }
    }
    if(packageCount < 2 || packageCount > 6) {
      this.setData({
        tip: 'paytip'
      })
      return
    }
    if(hasRedeem && redeemCount != 1) {
      this.setData({
        tip: 'redeemtip'
      })
      return
    }
    let cartProducts = []
    let cartRedeem = {}
    let sumPrice = 0
    let mySumPrice = 0
    console.log(this.data.cart.items)
    for(let m = 0; m < this.data.cart.items.length; m++) {
      for(let n = 0; n < this.data.products.length; n++) {
        if(this.data.cart.items[m] == this.data.products[n]['id'] && this.data.products[n].type == 1) {
          cartProducts.push(this.data.products[n])
          sumPrice += this.data.products[n].marketprice
          mySumPrice += this.data.products[n].my_price
          break
        }
        if(this.data.cart.items[m] == this.data.products[n]['id'] && this.data.products[n].type == 2) {
          cartRedeem = this.data.products[n]
          sumPrice += this.data.products[n].marketprice
          mySumPrice += this.data.products[n].my_price == null ? 0 : this.data.products[n].my_price
          break
        }
      }
    }
    if(cartRedeem.id !== undefined) {
      cartProducts.push(cartRedeem)
    }
    toast.show()
    mall.saveOrder({
      type: 1,
      address: '',
      products: JSON.stringify(cartProducts)
    }, r => {
      if(r.code == 200) {
        storage.remove('cart_items').then(() => {
          navigate.to(`/pages/mall/package/settlement/index?order_id=${r.order_id}`)
        })
      } else {
        this.setData({
          tip: 'error_tip',
          tipData: r.data
        })
      }
    }, r => {
      this.setData({
        tip: 'error_tip',
        tipData: `系统错误，请稍后再试~`
      })
    })
  },
  showRegisterTip: function() {
    this.setData({
      tip: 'register',
      tipData: `欢迎光临Hello Baby待产包，马上注册成为A+妈妈会员，尊享更多会员权益！`
    })
  },
  showRule: function() {
    this.setData({
      tip: 'rule'
    })
  },
  closeTip: function() {
    this.setData({
      tip: 'blank'
    })
  },
  goRegister: function() {
    navigate.redirect(`/pages/register/index?from=${encodeURIComponent(`../mall/index`)}`)
  },
  goIndex: function() {
    navigate.redirect('/pages/index/index')
  }
})